// pages/pay/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    orderList: [],
    totalPrice: 0,
    isShow: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getDataFromCart();
    this.FixedPrice();
    this.getTotalPrice();
  },

  getDataFromCart() {
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('acceptData', (data) => {
      console.log(data);
      this.setData({
        orderList: data.orderList,
      });
    });
  },
  getTotalPrice() {
    let { orderList, totalPrice } = this.data;
    orderList.forEach((val) => {
      totalPrice = Number(totalPrice) + Number(val.goods_price);
    });
    this.setData({
      totalPrice: this.toFixed(totalPrice, 2),
    });
  },
  getAddress() {
    wx.chooseAddress({
      success: (res) => {
        console.log(res);
        wx.setStorageSync('address', { data: res, time: new Date().getTime() });
        this.setData({
          address: res,
          isShow: false,
        });
      },
    });
  },
  FixedPrice() {
    let { orderList } = this.data;
    for (let i = 0; i < orderList.length; i++) {
      orderList[i].goods_price = this.toFixed(orderList[i].goods_price, 2);
    }
    this.setData({
      orderList,
    });
  },
  toFixed(str, n) {
    return str.toFixed(n);
  },
  pay() {
    wx.switchTab({
      url: '../user/index',
      complete: function () {
        wx.showToast({
          title: '付款成功',
        });
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    const addressData = wx.getStorageSync('address');
    if (addressData !== '') {
      this.setData({
        isShow: false,
        address: addressData.data,
      });
    } else {
      this.setData({
        isShow: true,
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
